<?php

namespace Tasker\Components\Forms;

use \Nette\Application\UI\Control,
	\Nette\Application\UI\Form;

/**
 * @property-read \BasePresenter $presenter
 */
class TaskForm extends Control
{

	private $id;
	public $project;
	public $milestone;
	private $redirect;

	public function render(array $values)
	{
		$dir = dirname($this->reflection->fileName);
		$this->template->setFile($dir . '/taskForm.latte');
		if (!isset($values['id']) && !isset($values['project']))
			throw new \Nette\InvalidArgumentException("Project or Task must be specified.");
		if (isset($values['id']))
		{
			$this->id = $values['id'];
			$taskModel = $this->presenter->context->models->task->find($this->id);
			$task = iterator_to_array($taskModel->getTask());
			$this->project = $task['project_id'];
			$task['prerequisites'] = array();
			foreach($taskModel->getPrerequisites() as $prerequisite){
				$task['prerequisites'][$prerequisite['prerequisite_id']] = array(
					'member' => $prerequisite['prerequisite_id'],
					'role' => $prerequisite['dependency_type'],
				);
			}
			$this['editForm']->setValues($task);
		}
		if (isset($values['project']))
		{
			$this->project = $values['project'];
		}
		$this['editForm']['id']->setValue($this->id);
		$this['editForm']['project_id']->setValue($this->project);
		$this->template->render();
	}

	public function setRedirect($redirect)
	{
		$this->redirect = $redirect;
	}

	protected function createComponentEditForm($name)
	{
		$form = new Form($this, $name);

		$form->addHidden('id');
		$form->addHidden('project_id');
		$form->addHidden('creator_id');

		if ($this->id === null)
			$this->id = $form['id']->getValue();
		if ($this->project === null)
			$this->project = $form['project_id']->getValue();


		$form->addText('name', 'Název:')
				->setRequired('Název úkolu je povinný');

		$projectModel = $this->presenter->context->models->project->find($this->project);
		$taskContextModel = $this->presenter->context->models->taskContext;

		$milestones = $projectModel->getMilestones()->fetchPairs('id', 'name');

		$form->addSelect('milestone_id', 'Milník:', $milestones)->setPrompt('# Žádný milník #');

		$members = array();
		foreach ($projectModel->getProjectTeam() as $member)
		{
			$members[$member['user_id']] = $member->user['name'] . ' ' . $member->user['surname'];
		}

		$form->addSelect('worker_id', 'Realizátor:', $members);
		$form->addDatePicker('start', 'Začátek:');
		$form->addDatePicker('deadline', 'Deadline:');
		$form->addRadioList('public', 'Veřejný:', array('yes' => 'Ano', 'no' => 'Ne'))
				->setDefaultValue('yes')
				->getSeparatorPrototype()->setName('span');
		$taskTypes = $projectModel->getTaskTypes()->fetchPairs('task_type.id', 'task_type.name');
		$form->addSelect('task_type_id', 'Typ úkolu:', $taskTypes);

		$priorities = $taskContextModel->getPriorities()->fetchPairs('id', 'name');
		$form->addSelect('task_priority_id', 'Priorita', $priorities);

		$statuses = $taskContextModel->getStatuses()->fetchPairs('id', 'name');
		$form->addSelect('task_status_id', 'Stav úkolu:', $statuses);

		$form->addTextArea('description', 'Popis:');


		$tasks = $projectModel->getTasks(array('NOT id'=>$this->id))->fetchPairs('id', 'name');
		$dependencies = array(
			'finish-to-start' => 'Úkol nemůže začít, dokud předchozí neskončí',
			'finish-to-finish' => 'Úkol nemůže skončit, dokud předchozí neskončí',
			'start-to-start' => 'Úkol nemůže začít, dokud předchozí nezačne',
			'start-to-finish' => 'Úkol nemůže skončit, dokud předchozí nezačne',
		);
		$form->addCheckboxDetailList('prerequisites', 'Závisí na:', $tasks, $dependencies);


		$form->addSubmit('send', 'Uložit');
		$form->onSuccess[] = callback($this, 'taskFormSubmitted');
		return $form;
	}

	public function taskFormSubmitted(Form $form)
	{
		$values = $form->getValues();
		if($values['creator_id'] === "")
			$values['creator_id'] = $this->presenter->user->id;
		
		if ($this->id !== "" && $this->id !== NULL)
		{ // Task is edited
			if($this->presenter->context->models->tasks->editTask($values)!== false){
				$this->getPresenter()->flashMessage('Úkol byl úspěšně upraven.');
			}else{
				$this->getPresenter()->flashMessage('Nastala chyba při úpravě úkolu.');
			}
		} else
		{ // New task
			if($this->presenter->context->models->tasks->addTask($values)){
				$this->getPresenter()->flashMessage('Úkol byl úspěšně vytvořen');
			}else{
				$this->getPresenter()->flashMessage('Nastala chyba při vytváření úkolu.');
			}
		}
		
		if($this->redirect !== null){
			$this->getPresenter()->redirectUrl($this->redirect);
		}else{
			$this->getPresenter()->redirect('Task:task',$id);
		}
	}

}
